package com.zixun.controller.web;

import com.zixun.model.User;
import com.zixun.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by Swinglife on 16/9/14.
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping("edit")
    public ModelAndView edit(Integer status,String nickName,Integer userId){
        ModelAndView mav = new ModelAndView(("redirect:list"));
        User user = userRepository.findById(userId);
        user.setNickName(nickName);
        user.setStatus(status);
        userRepository.save(user);
        return mav;
    }

    @RequestMapping("toEdit")
    public ModelAndView toEdit(Integer userId){
        ModelAndView mav = new ModelAndView("user/edit");
        User user = userRepository.findById(userId);
        mav.addObject("user",user);
        return mav;
    }

    @RequestMapping("list")
    public ModelAndView list(@RequestParam(value="page",defaultValue = "1")Integer page){
        ModelAndView mav = new ModelAndView("user/list");
        System.out.println(":"+userRepository);
        Page<User> userPage = userRepository.findAll(new PageRequest(page-1, 10));
        mav.addObject("totalPage",userPage.getTotalPages());
        mav.addObject("list",userPage);
        return mav;
    }

}
